/*
 * Title:        CloudScheduler Toolkit
 * Description:  a Toolkit for Modeling and Simulation of Job Scheduling and Resource Provisioning in Cloud System
 * Licence:      GPL - http://www.gnu.org/copyleft/gpl.html
 * Author:       Fuhui Wu
 *
 * Copyright (c) 2013-2014, The National University of Defense Technology, China
 */

package org.nudt.jCloud.simulation;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.ListIterator;

public class DeferredQueue {
	
	private final List<SimEvent> deferredEvents = new LinkedList<SimEvent>();
	private double maxTime = -1;
	
	public List<SimEvent> get(int id, int tag){
		List<SimEvent> searchedEvents = new ArrayList<SimEvent>();
		for(SimEvent simEvent : deferredEvents){
			if(simEvent.getDst()==id && simEvent.getTag()==tag){
				searchedEvents.add(simEvent);
			}
		}
		return searchedEvents;
	}
	
	public void removeEventList(List<SimEvent> simEventList){
		deferredEvents.removeAll(simEventList);
	}
	
	public void addEvent(SimEvent newEvent) {
		double eventTime = newEvent.getTime();
		if (eventTime >= maxTime) {
			deferredEvents.add(newEvent);
			maxTime = eventTime;
			return;
		}

		ListIterator<SimEvent> iterator = deferredEvents.listIterator();
		SimEvent event;
		while (iterator.hasNext()) {
			event = iterator.next();
			if (event.getTime() > eventTime) {
				iterator.previous();
				iterator.add(newEvent);
				return;
			}
		}

		deferredEvents.add(newEvent);
	}
	
	public int size(){
		return deferredEvents.size();
	}
	
	/**
	 * @return the list
	 */
	public List<SimEvent> getDeferredEvents() {
		return deferredEvents;
	}
	/**
	 * @return the maxTime
	 */
	public double getMaxTime() {
		return maxTime;
	}
	/**
	 * @param maxTime the maxTime to set
	 */
	public void setMaxTime(double maxTime) {
		this.maxTime = maxTime;
	}

	public Iterator<SimEvent> iterator() {
		return deferredEvents.iterator();
	}

}
